/**
 * 
 */
package goodroommate.service.impl;

import goodroommate.dal.DatabaseSession;
import goodroommate.dao.IUserDao;
import goodroommate.dao.impl.UserDao;
import goodroommate.domain.User;
import goodroommate.exception.AuthenticationFailedException;
import goodroommate.exception.DatabaseException;
import goodroommate.exception.ItemAlreadyExistsException;
import goodroommate.exception.ItemNotExistsException;
import goodroommate.service.IUserService;

/**
 * @author ZhouWuAi
 *
 */
public class UserService implements IUserService {

	IUserDao userDao=new UserDao();
	@Override
	public User login(String username, String password) throws DatabaseException, ItemNotExistsException ,AuthenticationFailedException{
		// TODO Auto-generated method stub
		try(DatabaseSession dbs=new DatabaseSession()){
			User user=userDao.getUserByUsername(dbs, username);
			if(user==null)
				throw new ItemNotExistsException();
			if(!user.getPassword().equals(password))
				throw new AuthenticationFailedException();
			return user;
		}
	}

	@Override
	public User register(String username, String password) throws DatabaseException, ItemAlreadyExistsException {
		// TODO Auto-generated method stub
		try(DatabaseSession dbs=new DatabaseSession()){
			if(userDao.checkUserExistenceByUsername(dbs, username))
				throw new ItemAlreadyExistsException();
			User user=new User();
			user.setUsername(username);
			user.setPassword(password);
			userDao.addUser(dbs, user);
			if(!dbs.tryCommit())
				dbs.rollback();
			return user;
		}
	}

	@Override
	public User getUserById(long id) throws DatabaseException, ItemNotExistsException {
		User user=null;
		try(DatabaseSession dbs=new DatabaseSession()){
			user=userDao.getUserById(dbs, id);
			if(user==null)
				throw new ItemNotExistsException();
			return user;	
		}catch(DatabaseException e){
			e.printStackTrace();
			throw new DatabaseException(e);
		}
	}
	

}
